import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/core/extentions/datetime_extern.dart';
import 'package:casdon/modules/me/application/notification/image_picker_notifier.dart';
import 'package:casdon/modules/me/application/notification/take_photos_notifier.dart';
import 'package:casdon/modules/me/application/notification/user_info_notifier.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';


final refreshProvider = StateProvider.autoDispose<UniqueKey>(
  (ref) => UniqueKey(),
);

@RoutePage()
class MeInfoScreen extends ConsumerStatefulWidget {
  const MeInfoScreen({super.key});

  @override
  ConsumerState<MeInfoScreen> createState() => _MeInfoScreenState();
}

class _MeInfoScreenState extends ConsumerState<MeInfoScreen> {
  bool _uploadStarted = false;

  @override
  void initState() {
    super.initState();
    Future.microtask(() async {
      await ref.read(userInfoNotifierProvider.notifier).fetchData();
    });
  }

  @override
  Widget build(BuildContext context) {
    ref.watch(refreshProvider);

    final userInfoState = ref.watch(userInfoNotifierProvider);
    return PopScope(
      canPop: true,
      onPopInvoked: (didPop) {
        if (didPop && !_uploadStarted) {
          _uploadStarted = true;
          unawaited(
            ref.read(userInfoNotifierProvider.notifier).uploadUserInfo(),
          );
        }
      },
      child: Scaffold(
        appBar: CommonAppBar(title: "账号资料"),
        body: Container(
          color: context.colorScheme.surface,
          child: Column(
            children: [
              _buildGap(context),
              FormFieldItem(
                label: '头像',
                isRequired: false,
                isEditable: false,
                showArrow: true,
                backgroundColor: Colors.white,
                trailing: CircleAvatarButton(
                  imageUrl: userInfoState.userAvatars,
                  defaultImage: AssetImage(Assets.images.icAvatar.path),
                  size: 36.w,
                  onPressed: () {
                    // _handleChangeAvatar(context, ref);
                    _showImagePickerActionSheet(context, ref);
                  },
                ),
                onTap: () => {_handleChangeAvatar(context, ref)},
              ),

              FormFieldItem(
                label: '昵称',
                isRequired: false,
                hintText:
                    (userInfoState.nickName == null ||
                        userInfoState.nickName!.isEmpty)
                    ? "未设置"
                    : null,
                value:
                    (userInfoState.nickName == null ||
                        userInfoState.nickName!.isEmpty)
                    ? null
                    : userInfoState.nickName,
                showArrow: true,
                isEditable: false,
                backgroundColor: Colors.white,
                onTap: () => _handleChangeNickName(context, ref),
              ),

              FormFieldItem(
                label: '性别',
                hintText: (userInfoState.sex.isEmpty) ? "未设置" : null,
                value: (userInfoState.sex.isEmpty)
                    ? null
                    : userInfoState.sex == "0"
                    ? "男"
                    : "女",
                isRequired: false,
                isEditable: false,
                showArrow: true,
                backgroundColor: Colors.white,
                onTap: () => _handleChangeSex(context, ref),
              ),
              FormFieldItem(
                label: '生日',
                hintText:
                    (userInfoState.birthday == null ||
                        userInfoState.birthday!.isEmpty)
                    ? "未设置"
                    : null,
                value:
                    (userInfoState.birthday == null ||
                        userInfoState.birthday!.isEmpty)
                    ? null
                    : userInfoState.birthday!.split(' ').first,
                isRequired: false,
                isEditable: false,
                showArrow: true,
                backgroundColor: Colors.white,
                onTap: () => _handleChangeBirthday(context, ref),
              ),

              _buildGap(context),

              FormFieldItem(
                label: '账号',
                value: userInfoState.userName,
                isRequired: false,
                isEditable: false,
                showArrow: true,
                showBottomDivider: false,
                backgroundColor: Colors.white,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGap(BuildContext context) {
    return ColoredBox(
      color: context.colorScheme.surface,
      child: SizedBox(height: 8, width: double.infinity),
    );
  }

  void _handleChangeAvatar(BuildContext context, WidgetRef ref) async {
    final ret = await ref.read(cameraProvider.notifier).takePhoto();
    if (ret != null) {
      ref.read(userInfoNotifierProvider.notifier).updateUserAvaTars(ret);
    }
  }

  void _handleChangeNickName(BuildContext context, WidgetRef ref) async {
    final result = await showInputDialog(
      context: context,
      title: '昵称',
      hintText: '输入新昵称',
    );
    if (result != null) {
      ref.read(userInfoNotifierProvider.notifier).updateNickName(result);
    }
  }

  void _handleChangeSex(BuildContext context, WidgetRef ref) {
    Pickers.showSinglePicker(
      context,
      data: ['男', '女'],
      selectData: "男",
      onConfirm: (p, position) {
        ref.read(userInfoNotifierProvider.notifier).updateSex("$position");
      },
    );
  }

  void _handleChangeBirthday(BuildContext context, WidgetRef ref) {
    DatePicker.showDatePicker(
      context,
      showTitleActions: true,
      minTime: DateTime(1925, 1, 1),
      maxTime: DateTime.now(),
      currentTime: DateTime.now(),
      locale: LocaleType.zh,
      onConfirm: (date) {
        ref
            .read(userInfoNotifierProvider.notifier)
            .updateBirthDay(date.formattedBeijingTime("yyyy-MM-dd"));
      },
    );
  }

  // 显示图片选择操作菜单
  void _showImagePickerActionSheet(BuildContext context, WidgetRef ref) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Container(
          color: Colors.transparent,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 操作选项卡片
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Column(
                  children: [
                    // 拍照选项
                    _buildActionItem(
                      title: '拍照',
                      onTap: () {
                        Navigator.pop(context);
                        _takePhoto();
                      },
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      height: 0.5,
                      color: Colors.grey[300],
                    ),
                    // 从手机相册选择
                    _buildActionItem(
                      title: '从手机相册选择',
                      onTap: () {
                        Navigator.pop(context);
                        _pickFromGallery();
                      },
                    ),
                  ],
                ),
              ),
              SizedBox(height: 8.h),
              // 取消按钮卡片
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: _buildActionItem(
                  title: '取消',
                  textColor: Color(0xFFD54941),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

  // 构建操作项
  Widget _buildActionItem({
    required String title,
    Color textColor = Colors.black,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Container(
        width: double.infinity,
        height: 56.h,
        alignment: Alignment.center,
        child: Text(
          title,
          style: context.textTheme.headlineLarge!.copyWith(color: textColor),
        ),
      ),
    );
  }

  // 拍照功能
  void _takePhoto() {
    print('执行拍照功能');
    _handleChangeAvatar(context, ref);
  }

  // 从相册选择
  Future<void> _pickFromGallery() async {
    final notifier = ref.read(imagePickerNotifierProvider.notifier);

    // 配置：仅图片，最多选择1张
    final config = const ImagePickerConfig(
      pickerType: PickerType.imageOnly,
      maxImages: 1,
    );

    final result = await notifier.pickFromGallery(
      context: context,
      config: config,
    );

    if (result != null && result.images.isNotEmpty && mounted) {
      // 更新用户头像（选择的第一张图片）
      ref
          .read(userInfoNotifierProvider.notifier)
          .updateUserAvaTars(result.images.first.path);
    }
  }
}
